package rewardsonline.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Description;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.tiles3.TilesConfigurer;

import rewardsonline.accounts.AccountsExcelView;
import rewardsonline.accounts.JsonViewResolver;

@Configuration
@EnableWebMvc // disables Spring Boot's MVC auto-configuration
public class MvcConfig extends WebMvcConfigurerAdapter {

	/**
	 * Define controllers which only render pages (i.e. nothing added to the 
	 * model)
	 */
	@Override
	public void addViewControllers(ViewControllerRegistry registry) {
		registry.addViewController("/").setViewName("welcome");
		registry.addViewController("/home").setViewName("welcome");
	}
	
	/**
	 * Serve static resources (JS, CSS, images)
	 */
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/**")
		        .addResourceLocations("/","classpath:/META-INF/","classpath:/web-resources/");
	}
	
	@Override
	public void configureViewResolvers(ViewResolverRegistry registry) {
		registry.enableContentNegotiation(true); // Enable a CNVR
		registry.beanName(); // Register a bean-name view resolver
		registry.tiles(); // Tiles view resolver
		registry.viewResolver(new JsonViewResolver()); // Custom resolver
	}
	
	/**
	 * Simple strategy: only path extension is taken into account (the default)
	 */
	@Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
		configurer.ignoreAcceptHeader(true);
		configurer.defaultContentType(MediaType.TEXT_HTML);
		
		// These are not strictly necessary, but were needed during the lab to 
		// demonstrate the 406 error
		configurer.mediaType("html", MediaType.TEXT_HTML);
        configurer.mediaType("json", MediaType.APPLICATION_JSON);
        configurer.mediaType("xls", new MediaType("application", "vnd.ms-excel"));
    }
	
	@Bean
	TilesConfigurer tilesConfigurer() {
		TilesConfigurer tilesConfigurer = new TilesConfigurer();
		tilesConfigurer.setDefinitions("/WEB-INF/tiles.xml");
		return tilesConfigurer;
	}
	

	@Bean(name="accounts/list")
	@Description("A view that generates a Account report as an Excel spreadsheet")
	public AccountsExcelView accountsExcelView() {
		return new AccountsExcelView();
	}
	
}
